import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { RouteRecordRaw } from 'vue-router'
import router from '../router'
import { useUserStore } from './user'

export const usePermissionStore = defineStore('permission', () => {
  // 动态路由
  const routes = ref<RouteRecordRaw[]>([])
  
  // 菜单权限
  const menuPermissions = ref<string[]>([])
  
  // 按钮权限
  const buttonPermissions = ref<string[]>([])
  
  // 数据权限
  const dataPermissions = ref<string[]>([])
  
  // 用户可访问的路由
  const accessRoutes = computed(() => routes.value)
  
  // 生成路由
  const generateRoutes = async () => {
    const userStore = useUserStore()
    
    try {
      // 获取路由表
      const accessedRoutes = filterAsyncRoutes(router.options.routes as RouteRecordRaw[], userStore.userInfo.roles)
      
      // 更新路由
      routes.value = accessedRoutes
      
      // 动态添加路由
      accessedRoutes.forEach(route => {
        if (!router.hasRoute(route.name as string)) {
          router.addRoute(route)
        }
      })
      
      return accessedRoutes
    } catch (error) {
      console.error('生成路由失败:', error)
      return []
    }
  }
  
  // 过滤异步路由
  const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
    const res: RouteRecordRaw[] = []
    
    routes.forEach(route => {
      const tmp = { ...route }
      
      // 检查用户角色是否有权限访问该路由
      if (hasPermission(roles, tmp)) {
        // 递归处理子路由
        if (tmp.children) {
          tmp.children = filterAsyncRoutes(tmp.children, roles)
        }
        res.push(tmp)
      }
    })
    
    return res
  }
  
  // 检查权限
  const hasPermission = (roles: string[], route: RouteRecordRaw) => {
    if (route.meta && route.meta.roles) {
      // 如果路由定义了角色要求，检查用户是否拥有其中任一角色
      return roles.some(role => (route.meta?.roles as string[]).includes(role))
    } else {
      // 如果路由没有定义角色要求，则所有用户都可访问
      return true
    }
  }
  
  // 设置权限
  const setPermissions = (menu: string[], button: string[], data: string[]) => {
    menuPermissions.value = menu
    buttonPermissions.value = button
    dataPermissions.value = data
  }
  
  // 检查是否有菜单权限
  const hasMenuPermission = (permission: string) => {
    return menuPermissions.value.includes(permission)
  }
  
  // 检查是否有按钮权限
  const hasButtonPermission = (permission: string) => {
    return buttonPermissions.value.includes(permission)
  }
  
  // 检查是否有数据权限
  const hasDataPermission = (permission: string) => {
    return dataPermissions.value.includes(permission)
  }
  
  return {
    routes,
    menuPermissions,
    buttonPermissions,
    dataPermissions,
    accessRoutes,
    generateRoutes,
    setPermissions,
    hasMenuPermission,
    hasButtonPermission,
    hasDataPermission
  }
})